<template>
  <fragment>
    <div
      @mouseenter="cellMouseEnter"
      @click="editCell"
      @mouseleave="cellMouseLeave"
      class="my_cell"
    >
      {{ content }}
    </div>

    <!-- style="display: none; width:240px" -->
    <el-input
      @blur="showCell"
      @keydown.enter.native="showCell"
      v-model="content"
      @input="handleChange"
    ></el-input>
  </fragment>
</template>

<script>
export default {
  model: {
    prop: "content",
    event: "change",
  },
  props: ["content", "disable"],
  name: "TableCell",
  methods: {
    // 鼠标进入单元格的回调
    cellMouseEnter(e) {
      e.target.classList.add("cellHover");
    },
    // 鼠标离开单元格的回调
    cellMouseLeave(e) {
      e.target.classList.remove("cellHover");
    },
    // 单击单元格的回调，用于打开输入模式
    editCell(e) {
      // console.log(this.props)
      const disable = this.disable || false;
      // console.log("@@@", disable);
      if (disable) return;
      const showDOM = e.target;
      const inputDOM = showDOM.nextSibling;
      showDOM.style.display = "none";
      inputDOM.style.display = "inline-block";
      inputDOM.querySelector("input").focus();
    },
    // 用于关闭输入模式
    showCell(e) {
      const inputDOM = e.target.parentNode;
      const showDOM = inputDOM.previousSibling;
      showDOM.style.display = "inline-block";
      inputDOM.style.display = "none";
    },
    // 与父组件通信
    handleChange(e) {
      // 关键 能实际把子组件中改变的值发给父组件，让父组件可见
      this.$emit("change", e.target.value);
    },
  },
};
</script>

<style lang='less' scoped>
.my_cell {
  width: 100%;
  height: 40px;
  line-height: 40px;
  // padding: 0 15px;
  color: #606266;
  border: 1px solid transparent;
  border-radius: 4px;
  font-size: inherit;
  transition: border 0.2s linear;
}
.el-input {
  width: 100%;
  display: none;
}
.cellHover {
  border: 1px solid #dcdfe6;
}
</style>